package com.itpan.Controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.itpan.Entity.Dto.EmployeeProcedure;
import com.itpan.Entity.Dto.newpassword;
import com.itpan.Entity.Employee;
import com.itpan.Entity.EmployeeDto;
import com.itpan.Entity.Product;
import com.itpan.Service.EmployeeService;
import com.itpan.Service.PurchaseOrderService;
import com.itpan.Utils.EmployeeExcelListener;
import com.itpan.Utils.EntityValidate;
import com.itpan.Utils.ImgUtils;

import com.itpan.common.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

/**
 * 2024/6/19 修改：进行优化和缓存处理
 */

@Slf4j
@RestController
@RequestMapping("/employee")
@Api(value = "员工接口")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private ImgUtils imgUtils;

    @Autowired
    private PurchaseOrderService purchaseOrderService;

    @Autowired
    private EntityValidate entityValidate;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Cacheable(value = "employee",key = "'all'")
    @GetMapping("/getall")
    public List<Employee> getAllEmployee(){
        return employeeService.getAllEmployee();
    }

    @ApiOperation(value = "表格下载")
    @RequestMapping(value = "/getall1", method = RequestMethod.GET)
    public void exportMemberList(HttpServletResponse response) throws IOException {
        setExcelRespProp(response, "会员列表");
        List<Employee> memberList = employeeService.getAllEmployee();
        EasyExcel.write(response.getOutputStream(), Employee.class)
                .excelType(ExcelTypeEnum.XLSX)
                .sheet("员工列表")
                .doWrite(memberList);
        response.getOutputStream().flush();  // Ensure all data is written to the response
    }


    @CacheEvict(value = "employee",allEntries = true)
    @ApiOperation(value = "批量导入")
    @PostMapping("/import")
    public String importEmployeeList(@RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return "文件不能为空";
        }
        EasyExcel.read(file.getInputStream(), Employee.class, new EmployeeExcelListener(entityValidate, employeeService))
                .excelType(ExcelTypeEnum.XLSX)
                .sheet()
                .doRead();
        return "文件上传成功";
    }

    /*
    新增一个员工
     */
    @CacheEvict(value = "employeecache",allEntries = true)
    @PostMapping("/add")
    @ApiOperation(value = "新增一个员工")
    public R<String> insetone(@ModelAttribute EmployeeDto employeeDto,@RequestParam("file") MultipartFile file){
        log.info("接受到员工：{}",employeeDto);
//        System.out.println(employeeDto.getFile());
//      //图片转换
        Employee employee = imgUtils.saveImgAndGetEmployee(employeeDto,file);

        if (!entityValidate.isValidateOfEmployee(employee)){
            return R.error("信息填写错误");
        }

        employeeService.saveOne(employee);
        return R.success("新增成功");
    }

    /*
    查询所有员工,没有分页
     */
    @Cacheable(value = "employeecache",key = "'all'")
    @ApiOperation(value = "查询所有员工")
    @GetMapping("list")
    public R<List<Employee>> list(){
        log.info("查所有员工");
        List<Employee> list=employeeService.getAllEmployee();
        return R.success(list);
    }

    /*
    查询所有员工，有分页
     */
    @Cacheable(value = "employee",key = "#p0"+'-'+"#p1")
    @ApiOperation(value = "查询所有员工带分页")
    @GetMapping("/listpage")
    public R<List<Employee>> listPage(Integer page,Integer pageSize){
        log.info("分页查询所有员工");
        if(page!=null && pageSize!=null){
            return R.success(employeeService.getAllEmployeePage(page,pageSize));
        }
        return R.error("查询失败");
    }


    /*
    模糊查询
     */
    @ApiOperation(value = "模糊查询不带表格")
    @PostMapping("/getbymutil")
    public R<List<Employee>> getbymutil(@RequestBody Employee employee){
        List<Employee> list = employeeService.getbymutil(employee);
        return R.success(list);
    }


    /*
    模糊查询带表格
     */

    @ApiOperation(value = "模糊查询带表格")
    @PostMapping("/getbymutiltable")
    public void getbymutiltable(@RequestBody Employee employee,HttpServletResponse response) throws IOException {
        List<Employee> list = employeeService.getbymutil(employee);
        setExcelRespProp(response, "员工列表");
        EasyExcel.write(response.getOutputStream(), Employee.class)
                .excelType(ExcelTypeEnum.XLSX)
                .sheet("员工列表")
                .doWrite(list);
        response.getOutputStream().flush();  // Ensure all data is written to the response
    }



    /*
    根据用户名查询详细信息：

     */
    @ApiOperation(value = "根据员工名字查询详细信息")
    @GetMapping("/getbyname")
    @Cacheable(value = "employee",key = "#p0")
    public R<Employee> findById(String employeeName){
        return R.success(employeeService.findByName(employeeName));
    }



    /*
    根据id修改一个员工信息
     */
    @ApiOperation(value = "修改一个员工")
    @PostMapping("/update")
    @CacheEvict(value = "employee",allEntries = true)
    public R<String> update(@ModelAttribute EmployeeDto employeeDto,@RequestParam("file") MultipartFile file){

        Employee employee = imgUtils.saveImgAndGetEmployee(employeeDto,file);

        if (!entityValidate.isValidateOfEmployee(employee)){
            return R.error("信息填写错误");
        }



        employeeService.update(employee);
        return R.success("修改成功");
    }



    /*
    删除一个员工信息
     */

    @ApiOperation(value = "删除一个员工")
    @DeleteMapping("/delete")
    @CacheEvict(value = "employee",allEntries = true)
    public R<String> delete(@RequestParam String id){

       List<Employee>list= purchaseOrderService.getbyempid(id);
        if(list.size()>0){
            return R.error("删除员工失败，员工还负责相应采购主表");
        }
        employeeService.deleteById(id);
        return R.success("删除成功");
    }


    /**
     * 根据员工等级查最高员工姓名  ：利用存储过程
     * @param level
     * @return
     */
    @ApiOperation("根据员工等级查询最高工资员工")
    @GetMapping("getsalaryoflevel/{level}")
    public  R< List<EmployeeProcedure>> getsalaryoflevel(@PathVariable(value = "level") Integer level)
    {
        List<EmployeeProcedure> list = employeeService.gettopsalaryoflevel(level);
        System.out.println(list);
        return R.success(list);

    }




    @ApiOperation("修改密码")
    @PostMapping("/updatepassword")
        public R<String> updatePassword(@RequestBody newpassword ne){

        if (ne.getEmployeeEmail()==null){
            return R.error("邮箱填写错误");
        }
            String o = (String) redisTemplate.opsForValue().get(ne.getEmployeeEmail());
            if(o==null){
                return R.error("验证码已经过期");
            }

            if(!ne.getPin().equals(o)){
                return R.error("验证码错误");
            }




            Employee em = employeeService.getemployeebyemail(ne.getEmployeeEmail());
                em.setEmployeePassword(ne.getEmployeePassword());
                employeeService.update(em);
                return R.success("修改成功");
        }




    /**
     * 设置excel下载响应头属性
     */
    private void setExcelRespProp(HttpServletResponse response, String rawFileName) throws UnsupportedEncodingException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode(rawFileName, "UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + fileName + ".xlsx");
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // Ensure the file is not cached
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Expires", "0");
    }
}
